package com.fanrenqiji.modules.sys.interceptor;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.service.BaseCommonService;
import com.fanrenqiji.common.utils.SpringContextHolder;
import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.modules.sys.dao.LogDao;
import com.fanrenqiji.modules.sys.entity.Log;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月26日 下午7:05:42
 * @description 系统拦截器
 */
public class LogInterceptor extends BaseCommonService implements HandlerInterceptor {
	/**
	 * 系统启动时候加载,不能使用注解注入。
	 */
	private static LogDao logDao = SpringContextHolder.getBean(LogDao.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 返回true
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 在通过请求最后执行日志记录，一般用在资源释放上，现在用在记录系统日志上
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 获得请求uri
		String requestUri = request.getRequestURI();
		// 获得配置的uri项目配置
		String uriPrefix = request.getContextPath()
				+ GlobalSetting.getAdminPath();

		if (StringUtils.startsWith(requestUri, uriPrefix)
				&& (StringUtils.endsWith(requestUri, "/save")
						|| StringUtils.endsWith(requestUri, "/delete")
						|| StringUtils.endsWith(requestUri, "/import") || StringUtils
							.endsWith(requestUri, "/updateSort")) || ex != null) {
			// 获得系统登陆的用户
			User user = UserUtils.getUser();
			// 判断用户是否为空
			if (user != null && user.getId() != null) {
				StringBuilder params = new StringBuilder();
				int index = 0;
				for (Object param : request.getParameterMap().keySet()) {
					params.append((index++ == 0 ? "" : "&") + param + "=");
					params.append(StringUtils.abbr(
							StringUtils.endsWithIgnoreCase((String) param,
									"password") ? "" : request
									.getParameter((String) param), 100));
				}
				
				// 添加日志记录
				Log log = new Log();
				log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
				log.setCreateBy(user);
				log.setCreateDate(new Date());
				log.setRemoteAddr(StringUtils.getRemoteAddr(request));
				log.setUserAgent(request.getHeader("user-agent"));
				log.setRequestUri(request.getRequestURI());
				log.setMethod(request.getMethod());
				log.setParams(params.toString());
				log.setException(ex != null ? ex.toString() : "");
				
				logger.info("save log {type: {}, loginName: {}, uri: {}}, ",
						log.getType(), user.getLoginName(), log.getRequestUri());
				
				logDao.save(log);
				
			}
		}

	}

}
